import { getUserInfo, login } from '../../api/user'
import { isLogin, login as loginPermission } from '../../utils/permission'

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLogin: false,
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._setLoginStatus()
    this.data.isLogin && this._getUserInfo()

    // 监听事件
    app.event.on('userInfoChanged', this._setUserInfo)
    app.event.on('loginStatusChanged', this._setLoginStatus)
  },

  onUnload: function () {
    app.event.removeListener('userInfoChanged', this._setUserInfo)
    app.event.removeListener('loginStatusChanged', this._setLoginStatus)
  },

  _setUserInfo: function () {
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },

  _setLoginStatus: function () {
    this.setData({
      isLogin: isLogin()
    })
  },

  _getUserInfo: function () {
    getUserInfo().then((res) => {
      if (res.code == 200) {
        app.setUserInfo(res.data)
      }
    })
  },

  _userInfoTap: function () {
    let params = {
      code: '',
      iv: '',
      encryptedData: ''
    }
    wx.getUserProfile({
      desc: '用于完善用户资料'
    })
      .then((res) => {
        params.iv = res.iv
        params.encryptedData = res.encryptedData
        return wx.login().then((res) => {
          params.code = res.code
          return login(params)
        })
      })
      .catch(() => {})
  },

  _getPhoneNumber: function (e) {
    console.log(e)
    if (!e.detail.iv || !e.detail.encryptedData) return
    let params = {
      code: '',
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData
    }
    wx.login()
      .then((res) => {
        params.code = res.code
        return login(params)
      })
      .then((res) => {
        let user = {
          name: res.data.name,
          department: res.data.department
        }
        loginPermission(res.data.token, user)
        app.event.emit('loginStatusChanged')
        this._getUserInfo()
        if (!user.name || !user.department) {
          wx.navigateTo({
            url: '/pages/userInfo/fill/fill',
            success: function () {
              wx.showToast({
                title: '请完善个人信息'
              })
            }
          })
        }
      })
  }
})
